import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  computed,
  watch
} from 'vue';
import TableSearchSelect from '@/components/TableSearchSelect/index';
import Table from '@/components/Table/index';
import { rebuildObject } from '@/utils/util';
import { useStore } from '@/store';
import { ElMessage, ElMessageBox } from 'element-plus/lib/index';
import './style/index.scss';
import { ECustomColumn } from '@/utils/constants';
import { useRoute } from 'vue-router';
import SearchForm from '@/components/SearchForm/index';
import BatchOperates from '@/components/batchOperates/index.vue';
import CustomColumn from '@/components/CustomColumn/index';
import Bulk from '@/components/Bulk/index';
import { setFieldsValue } from '@/utils/util';
import PageFilter from '@/components/PageFilter/index';
import API from '@/services';
import _ from 'lodash';

const StatisticsLifecycle = defineComponent({
  name: 'StatisticsLifecycle',
  components: { BatchOperates },
  setup: (props, { slots, attrs, emit }) => {
    // 选择row
    const multipleSelection: any = reactive({ data: [] });
    // 取出对应 api。
    const {
      timePeriod: {
        postTimePeriodList,
        deleteTimePeriodById,
        postTimePeriod,
        putTimePeriodById
      },
      userInfoService: { getUser }
    } = API;
    const store = useStore();
    const visible = computed(() => store.state.statistics.drawerVisible);
    /* 表单 */
    const form = ref({});

    /* form实例 */
    const formRef: any = ref();

    const state = reactive({
      userList: [] as any[]
    });

    /* table loading */
    const TableLoading = ref(false);

    /* route */
    const route = useRoute();

    /* 名称重复字段及文案 */
    const errorData = ref([]);

    /* 编辑状态 */
    const isEdit = ref(false);

    /* 下载模版Url */
    const downloadUrl = ref('');

    /* table List */
    const tableList: any = reactive({
      list: [],
      total: 0,
      pageNum: 1,
      pageSize: 10
    });

    // 排序
    const sortParams = ref({});

    /* 自定义column */
    const tableColumn: any = ref([
      {
        keys: 1,
        sortable: true
      },
      {
        keys: 6,
        sortable: true
      },
      {
        label: '操作',
        keys: 8,
        default: ({ row }: any) => {
          return (
            <div>
              <el-button
                onClick={() => {
                  editItem(row);
                  isEdit.value = true;
                }}
                type="text"
              >
                编辑
              </el-button>
              <el-button
                disabled={!row.deletable}
                type="text"
                onClick={() => openDelete(row.id)}
              >
                删除
              </el-button>
            </div>
          );
        }
      }
    ]);

    /* table Column */
    const newTableColumn: any = ref([]);

    /* 自定义列表 */
    const settings: any = ref([]);

    // 编辑和新建的form
    const editItemObjForm: any = reactive({
      cnName: '',
      businessMeaning: '',
      enName: '',
      remarks: ''
    });
    const rules = {
      cnName: [
        { required: true, message: '请输入统计粒度名称', trigger: 'blur' }
      ],
      enName: [{ required: true, message: '请输入英文名称', trigger: 'blur' }],
      businessMeaning: [
        { required: true, message: '请输入业务含义', trigger: 'blur' }
      ]
    };
    const editRefFrom: any = ref();
    // 暂存删除id
    const deleteIdCont: any = ref();

    //筛选条件
    const pageFilter: any = ref([]);

    /* 获取筛选条件 */
    const getPageFilter = async () => {
      try {
        const { code, data }: any = await API.userPageFilterSetting.getFindOne({
          pageCode: ECustomColumn?.timeperiod
        });
        if (code === 200 && data) {
          let checkedArray: any[] = data.settings.filter((v: any) => v.isCheck);
          checkedArray.sort((a, b) => a.order - b.order);
          pageFilter.value = checkedArray;

          //初始化表单对象
          pageFilter.value.map((item: any) => {
            form.value[item.prop] = '';
          });
        }
      } catch (error) {
        console.log(error);
      }
    };

    //获取选项数据
    const getSelectData = (keys: any) => {
      switch (keys) {
        case 2:
          return {
            list: state.userList,
            isRemote: true,
            remoteMethod: (name: string) => getUserApi(name)
          };
        default:
          return;
      }
    };

    // 打开删除弹窗
    const openDelete = (id: number) => {
      deleteIdCont.value = id;
      ElMessageBox.alert('', '是否确认删除该统计粒度?', {
        confirmButtonText: '确认删除',
        showCancelButton: true,
        confirmButtonClass: 'message-box-del'
      })
        .then(async () => {
          try {
            const { code, data, msg } = await deleteTimePeriodById({
              id
            });
            if (code === 200) {
              getTableList();
              deleteIdCont.value = null;
              ElMessage.success('删除成功');
            } else {
              ElMessage.error(msg);
            }
          } catch (error) {
            console.log(error);
            ElMessage.error('删除失败');
          }
        })
        .catch(() => {
          ElMessage.info('取消删除');
        });
    };

    // 关闭抽屉
    const handleClose = () => {
      editItemObjForm.cnName = '';
      editItemObjForm.businessMeaning = '';
      editItemObjForm.enName = '';
      editItemObjForm.remarks = '';
      errorData.value = [];
      store.commit('statistics/toggleDrawerVisible', false);
    };

    // 编辑弹窗
    const editItem = (row: any) => {
      setFieldsValue(editItemObjForm, row);
      editItemObjForm['id'] = row?.id;
      store.commit('statistics/toggleDrawerVisible', true);
    };
    // 确认编辑和添加
    const comfrimEditAndCreat = () => {
      editRefFrom.value.validate((judge: boolean) => {
        if (judge) {
          if (isEdit.value) {
            // 编辑
            editDataFn();
          } else {
            // 新建
            newCreatFn();
          }
        } else {
          ElMessage.error('请检查字段信息');
        }
      });
    };
    // 新建
    const newCreatFn = async () => {
      try {
        const { code, data }: any = await postTimePeriod(editItemObjForm);
        if (code === 200) {
          ElMessage.success('创建成功');
          getTableList();
          handleClose();
        } else {
          errorData.value = data;
        }
      } catch (error) {
        ElMessage.error('创建失败');
      }
    };
    // 编辑
    const editDataFn = async () => {
      const params = { id: editItemObjForm.id };
      delete editItemObjForm['id'];
      try {
        const { code } = await putTimePeriodById(params, editItemObjForm);
        if (code === 200) {
          ElMessage.success('编辑成功');
          getTableList();
          handleClose();
        }
      } catch (error) {
        ElMessage.error('编辑失败');
      }
    };

    // 排序
    const sortTable = (obj: any) => {
      if (obj.prop) {
        const order = obj.order === 'ascending' ? 1 : 2;
        sortParams.value = { sortBy: obj.prop, order };
      } else {
        sortParams.value = {};
      }
    };

    // 获取table
    const getTableList = async () => {
      TableLoading.value = true;
      const params = {
        ...rebuildObject(form.value),
        ...sortParams.value,
        pageNum: tableList.pageNum,
        pageSize: tableList.pageSize
      };
      try {
        const { code, data } = await postTimePeriodList(params);
        if (code === 200 && Array.isArray(data?.list)) {
          tableList.list = data?.list;
          // 记录： total应后端改为number
          tableList.total = Number(data?.total);
          console.log(tableList.total);
        }
      } catch (error) {
        console.log(error);
      } finally {
        TableLoading.value = false;
      }
    };

    /* 获取用户 */
    const getUserApi = async (name?: string) => {
      try {
        const { code, data } = await getUser({ name });
        if (code === 200 && Array.isArray(data)) {
          state.userList = data;
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 名称重复字段及文案校验 */
    const errCheck = (label: string) => {
      const errKey = errorData.value?.map((v: any) => v.error_field);
      if (errKey?.includes(label)) {
        const errInfo: any = errorData.value?.filter(
          (v: any) => v.error_field === label
        );
        return new String(errInfo[0].error_msg);
      }
      return false;
    };

    watch(sortParams, () => {
      getTableList();
    });

    onMounted(() => {
      //自定义列表
      getCustomColumnApi();
      //用户列表
      getUserApi();
      getPageFilter();
      // table
      getTableList();
      if (route.query.modal) {
        store.commit('statistics/toggleDrawerVisible', true);
      }
    });

    const handleSelectionChange = (v: any) => {
      multipleSelection.data = v;
    };

    /* 获取自定义列列表 */
    const getCustomColumnApi = async () => {
      try {
        const { code, data }: any = await API.userPageSetting.getFindOne({
          pageCode: ECustomColumn?.timeperiod
        });
        if (code === 200) {
          settings.value = data?.settings;
          const column = data?.settings?.map((v: any, i: number) => {
            const columnIndex = tableColumn.value?.findIndex(
              (val: any) => val?.keys === v?.keys
            );
            console.log(columnIndex, 'columnIndex');
            return {
              ...tableColumn.value[columnIndex],
              ...v,
              columnKey: Date.now()
            };
          });
          column.unshift({
            type: 'selection',
            width: '55',
            isCheck: true
          });
          newTableColumn.value = _.compact(column);
          console.log(newTableColumn.value);
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 保存自定义列表 */
    const customColumnConfirm = async (vo: any) => {
      try {
        const { code } = await API.userPageSetting.postSave({
          pageCode: ECustomColumn?.timeperiod,
          settings: vo?.map(({ disabled, keys, isCheck, label, prop }: any) => {
            return {
              disabled,
              keys,
              isCheck,
              label,
              prop
            };
          })
        });
        if (code === 200) {
          ElMessage.success('保存配置成功');
          getCustomColumnApi();
        }
      } catch (error) {
        console.log(error);
      }
    };

    /* 批量操作 */
    const handleBatchOperate = async (v: any) => {
      const ids: any = multipleSelection?.data
        ?.filter((v: any) => v.deletable)
        .map((d: any) => d.id);
      switch (v) {
        case 'delete':
          if (!ids.length) {
            ElMessage.warning('批量删除失败');
            return;
          }
          TableLoading.value = true;
          ElMessageBox.alert('', '是否确认删除已选统计粒度?', {
            confirmButtonText: '确认删除',
            showCancelButton: true,
            confirmButtonClass: 'message-box-del'
          })
            .then(async () => {
              try {
                const { code, data, msg } =
                  await API.timePeriod.postTimePeriodBatchDelete(ids);
                if (code === 200) {
                  ElMessage.success('批量删除成功');
                } else {
                  // ElMessage.error(msg);
                }
                tableList.pageNum = 1;
                getTableList();
              } catch (error) {
                console.log(error);
                // ElMessage.error('批量删除失败');
              }
            })
            .catch(() => {
              ElMessage.info('批量取消删除');
            });
          TableLoading.value = false;
          break;
      }
    };

    return () => {
      return (
        <div class="statistics-container">
          <SearchForm
            num={4}
            onReset={() => {
              formRef.value.resetFields();
              getTableList();
            }}
            onSearch={() => getTableList()}
            model={form.value}
            formRef={formRef}
            isSearchBtn={false}
            v-slots={{
              pageFilter: () => (
                <>
                  {pageFilter.value.map((item: any) => {
                    return (
                      <el-form-item label={item.label + ':'} prop={item.prop}>
                        <PageFilter
                          searchForm={form.value}
                          pageSettings={item}
                          selectData={getSelectData(item.keys)}
                          onSearchForm={() => getTableList()}
                        ></PageFilter>
                      </el-form-item>
                    );
                  })}
                </>
              )
            }}
          ></SearchForm>

          <div class="table-operate">
            <div class="CustomColumn-operate-wrap">
              <CustomColumn
                onConfirm={(v: any) => customColumnConfirm(v)}
                tableColumn={settings.value}
              />
              <div class="checkLength">
                已选择<b>{multipleSelection.data.length}</b>个统计粒度
              </div>
            </div>
            <div class="batch-operate-wrap">
              <Bulk
                downloadList={[{ command: 'statistics', text: '统计粒度下载' }]}
                onCommand={() => {
                  downloadUrl.value = '/tmplate/download/';
                }}
                downloadUrl={downloadUrl.value}
                tmpCode={'4'}
                onSuccess={() => getTableList()}
              />
              <BatchOperates
                v-loading={TableLoading.value}
                opKeys={['delete']}
                onBatchOperate={handleBatchOperate}
                disabled={multipleSelection.data.length === 0}
              />
            </div>
          </div>

          <Table
            onSelectionChange={handleSelectionChange}
            v-loading={TableLoading.value}
            total={tableList.total}
            data={tableList.list}
            column={newTableColumn.value.filter((v: any) => v.isCheck)}
            onSortChange={sortTable}
            onPageCurrentChange={(page: number) => {
              tableList.pageNum = page;
              getTableList();
            }}
            onPageSizeChange={(size: number) => {
              tableList.pageNum = 1;
              tableList.pageSize = size;
              getTableList();
            }}
            pagination={{
              total: tableList.total,
              currentPage: tableList.pageNum,
              pageSize: tableList.pageSize
            }}
          />
          <el-drawer
            custom-class="statistics-drawer"
            close-on-click-modal={false}
            append-to-body={true}
            v-model={visible.value}
            title={isEdit.value ? '编辑统计粒度' : '创建统计粒度'}
            direction="rtl"
            before-close={handleClose}
            onClosed={() => (isEdit.value = false)}
            lock-scroll={false}
          >
            <el-form
              model={editItemObjForm}
              ref={editRefFrom}
              label-position={'right'}
              label-width="111px"
              rules={rules}
            >
              <el-row gutter={20}>
                <el-col span={22}>
                  <el-form-item
                    error={errCheck('cnName')}
                    label="统计粒度名称:"
                    prop="cnName"
                  >
                    <el-input
                      size="large"
                      disabled={isEdit.value}
                      v-model={editItemObjForm.cnName}
                      maxlength={20}
                      style={{ width: '100%' }}
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col span={22}>
                  <el-form-item
                    error={errCheck('enName')}
                    label="英文名称:"
                    prop="enName"
                  >
                    <el-input
                      size="large"
                      disabled={isEdit.value}
                      v-model={editItemObjForm.enName}
                      maxlength={60}
                      style={{ width: '100%' }}
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col span={22}>
                  <el-form-item label="业务含义:" prop="businessMeaning">
                    <el-input
                      type="textarea"
                      rows={3}
                      maxlength={200}
                      v-model={editItemObjForm.businessMeaning}
                      style={{ width: '100%' }}
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col span={22}>
                  <el-form-item label="备注:" prop="remarks">
                    <el-input
                      type="textarea"
                      rows={3}
                      maxlength={200}
                      v-model={editItemObjForm.remarks}
                      style={{ width: '100%' }}
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div class="footer-btn">
              <el-button onClick={handleClose}>取 消</el-button>
              <el-button onClick={comfrimEditAndCreat} type="primary">
                确定
              </el-button>
            </div>
          </el-drawer>
        </div>
      );
    };
  }
});

export default StatisticsLifecycle;
